package com.xms.schema.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xms.core.model.PagedList;
import com.xms.schema.core.RelationShipType;
import com.xms.schema.entity.Entity;
import com.xms.schema.service.entity.IEntityFinderService;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
 * <p>
 * EntityCreaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/1
 */

@RestController
@RequestMapping("{org}/api/schema/entity")
public class EntityFinderController extends ApiBaseController {
    private IEntityFinderService _entityFinderService;
    @Autowired
    public EntityFinderController(IEntityFinderService entityFinderService) {
        _entityFinderService = entityFinderService;
    }

    @ApiOperation("查询实体元数据列表")
    @GetMapping(value = "list")
    public JsonResultObject get(@RequestParam(required = false) String name,
                                @RequestParam(value="entitygroupid", required = false) String entitygroupid,
                                @RequestParam(value="isauthorization", required = false) Boolean isauthorization,
                                @RequestParam(value="iscustomizable", required = false) Boolean iscustomizable,
                                @RequestParam(value="logenabled", required = false) Boolean logenabled,
                                @RequestParam(value="duplicateenabled", required = false) Boolean duplicateenabled,
                                @RequestParam(value="workflowenabled", required = false) Boolean workflowenabled,
                                @RequestParam(value="getall", required = false) Boolean getall,
                                @RequestParam(value="page", required = false) Integer page,
                                @RequestParam(value="pagesize", required = false) Integer pagesize,
                                @RequestParam(value="sortby", required = false) String sortby,
                                @RequestParam(value="sortdirection", required = false) String sortdirection) {

        LambdaQueryWrapper<Entity> lambdaQueryWrapper = getSortedQueryWrapper(sortby, sortdirection);;
        if (StringUtil.notEmpty(name)) {
            lambdaQueryWrapper.in(Entity::getName, name);
        }
        if (StringUtil.notEmpty(entitygroupid)) {
            if(entitygroupid.equalsIgnoreCase(("00000000-0000-0000-0000-000000000000"))){
                lambdaQueryWrapper.and(x->x.isNull(Entity::getEntitygroups).or().eq(Entity::getEntitygroups, ""));
            }
            else {
                lambdaQueryWrapper.like(Entity::getEntitygroups, entitygroupid);
            }
        }
        if (isauthorization != null) {
            lambdaQueryWrapper.eq(Entity::getAuthorizationenabled, isauthorization);
        }
        if (logenabled != null) {
            lambdaQueryWrapper.eq(Entity::getLogenabled, logenabled);
        }
        if (duplicateenabled != null) {
            lambdaQueryWrapper.eq(Entity::getDuplicateenabled, duplicateenabled);
        }
        if (workflowenabled != null) {
            lambdaQueryWrapper.eq(Entity::getWorkflowenabled, workflowenabled);
        }
        if (getall != null && getall) {
            return JOk(_entityFinderService.list(lambdaQueryWrapper));
        }
        else if(page == null || pagesize == null){
            return JNotSpecifiedParams("page","pagesize");
        }
        page = (page <= 0 ? 1 : page);
        pagesize = (pagesize <= 0 ? 10 : pagesize);
        IPage<Entity> datas = _entityFinderService.page(new Page<>(page, pagesize), lambdaQueryWrapper);
        PagedList<Entity> result = new PagedList<>(page, pagesize, datas.getTotal());
        result.items = datas.getRecords();
        result.totalpages = datas.getPages();
        return JOk(result);
    }

    @ApiOperation("查询实体名称是否存在")
    @GetMapping(value = "exists")
    public JsonResultObject exists(@RequestParam(value = "name", required = true) String name,
                                   @RequestParam(value = "entityid", required = false) UUID entityid) {
        boolean isExists = false;
        if(UUIDUtil.notEmpty(entityid)){
            isExists = _entityFinderService.existsName(name, entityid);
        }
        else{
            isExists = _entityFinderService.existsName(name);
        }
        return isExists ? JError() : JOk();
    }

    @ApiOperation("查询实体元数据")
    @GetMapping(value = "getbyid/{id}")
    public JsonResultObject getById(@PathVariable(value = "id", required = true) UUID id) {
        if(UUIDUtil.isEmpty(id)){
            return JNotSpecifiedParams("id");
        }
        Entity result = _entityFinderService.getById(id);
        return JOk(result);
    }

    @ApiOperation("按id查询多个实体元数据")
    @GetMapping(value = "getbyids/{id}")
    public JsonResultObject getByIds(@PathVariable(value = "id", required = true) String id) {
        if(StringUtil.isEmpty(id)){
            return JNotSpecifiedParams("id");
        }
        String[] idArr = StringUtil.splitSafe(id, ",");
        List<UUID> ids = new ArrayList<>();
        for (String s : idArr){
            if(StringUtil.notEmpty(s)){
                ids.add(UUIDUtil.get(s));
            }
        }

        return JOk(_entityFinderService.getByIds(ids));
    }

    @ApiOperation("查询实体元数据")
    @GetMapping(value = "/getbyname/{name}")
    public JsonResultObject getByName(@PathVariable("name") String name) {
        Entity result = _entityFinderService.getByName(name);
        return JOk(result);
    }

    @ApiOperation("按id查询多个实体元数据")
    @GetMapping(value = "getbynames/{name}")
    public JsonResultObject getByNames(@PathVariable(value = "name", required = true) String name) {
        if(StringUtil.isEmpty(name)){
            return JNotSpecifiedParams("name");
        }

        return JOk(_entityFinderService.getByNames(Arrays.asList(StringUtil.splitSafe(name, ","))));
    }

    @ApiOperation("多对一关联实体列表")
    @GetMapping(value = "/getmanytoone/{entityid}")
    public JsonResultObject GetManyToOne(@PathVariable("entityid") UUID entityid) {
        List<Entity> result = _entityFinderService.getRelatedEntities(entityid, RelationShipType.ManyToOne.value(), -1);

        return JOk(result);
    }

    @ApiOperation("一对多关联实体列表")
    @GetMapping(value = "/getonetomany/{entityid}")
    public JsonResultObject getOneToMany(@PathVariable("entityid") UUID entityid) {
        List<Entity> result = _entityFinderService.getRelatedEntities(entityid, RelationShipType.OneToMany.value(), -1);

        return JOk(result);
    }
}
